import { defineConfig } from "cypress";
import mysql from 'mysql2/promise';

// 数据库配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'book_sharing'
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

export default defineConfig({
  e2e: {
    baseUrl: 'http://localhost:5173', // Vite 开发服务器的默认地址
    setupNodeEvents(on, config) {
      // 数据库操作任务
      on('task', {
        // 清理测试用户数据
        async 'db:clean'(pattern) {
          const connection = await pool.getConnection();
          try {
            // 如果是模式匹配（包含 %），使用 LIKE；否则使用精确匹配
            const sql = pattern.includes('%') 
              ? 'DELETE FROM users WHERE username LIKE ?'
              : 'DELETE FROM users WHERE username = ?';
            
            await connection.execute(sql, [pattern]);
            return null;
          } finally {
            connection.release();
          }
        },

        // 验证用户是否被清理
        async 'db:verify'(pattern) {
          const connection = await pool.getConnection();
          try {
            const [rows] = await connection.execute(
              'SELECT COUNT(*) as count FROM users WHERE username LIKE ?',
              [pattern]
            );
            return rows[0].count;
          } finally {
            connection.release();
          }
        }
      });
    },
    defaultCommandTimeout: 10000,
    requestTimeout: 10000,
    responseTimeout: 10000,
    viewportWidth: 1280,
    viewportHeight: 720,
    video: false, // 禁用视频录制以提高测试速度
    screenshotOnRunFailure: true, // 测试失败时自动截图
    chromeWebSecurity: false
  },
});
